#include "stm32f10x.h"
#include "MySPI.h"
#include "W25Q64_Ins.h"

void W25Q64_Init(void) {
    MySPI_Init();
}

void W25Q64_ReadID(uint8_t* MID, uint16_t* DID) {
    MySPI_Start();
    MySPI_Transfer(W25Q64_JEDEC_ID);
    *MID = MySPI_Transfer(W25Q64_DUMMY_BYTE);
    *DID = MySPI_Transfer(W25Q64_DUMMY_BYTE) << 8; // 高8位
    *DID |= MySPI_Transfer(W25Q64_DUMMY_BYTE); // 低8位
    MySPI_Stop();
}

void W25Q64_WriteEnable(void) {
    MySPI_Start();
    MySPI_Transfer(W25Q64_WRITE_ENABLE);
    MySPI_Stop();
}

void W25Q64_WaitBusy(void) {
    uint32_t Timeout;
    MySPI_Start();
    MySPI_Transfer(W25Q64_READ_STATUS_REGISTER_1);
    Timeout = 100000;
    while ((MySPI_Transfer(W25Q64_DUMMY_BYTE) & 0x01) == 0x01 && Timeout-- > 0);
    MySPI_Stop();
}

void W25Q64_PageProgram(uint32_t Address, uint8_t* InputDatas, uint16_t Count) {
    W25Q64_WriteEnable();
    MySPI_Start();
    MySPI_Transfer(W25Q64_PAGE_PROGRAM);
    // 从高到低发送3位地址
    MySPI_Transfer(Address >> 16);
    MySPI_Transfer(Address >> 8);
    MySPI_Transfer(Address);
    // 发送数据
    for (uint16_t i = 0; i < Count; i++)
    {
        MySPI_Transfer(InputDatas[i]);
    }
    MySPI_Stop();
    W25Q64_WaitBusy();
}

void W25Q64_SectorErase(uint32_t Address) {
    W25Q64_WriteEnable();
    MySPI_Start();
    MySPI_Transfer(W25Q64_SECTOR_ERASE_4KB);
    MySPI_Transfer(Address >> 16);
    MySPI_Transfer(Address >> 8);
    MySPI_Transfer(Address);
    MySPI_Stop();
    W25Q64_WaitBusy();
}

void W25Q64_ReadData(uint32_t Address, uint8_t* OutputDatas, uint32_t Count) {
    MySPI_Start();
    MySPI_Transfer(W25Q64_READ_DATA);
    // 从高到低发送3位地址
    MySPI_Transfer(Address >> 16);
    MySPI_Transfer(Address >> 8);
    MySPI_Transfer(Address);
    // 接收数据
    for (uint32_t i = 0; i < Count; i++)
    {
        OutputDatas[i] = MySPI_Transfer(W25Q64_DUMMY_BYTE);
    }
    MySPI_Stop();
}
